package cn.schoolwow.quickdao.module.database.ddl.query.flow.index.getEntityIndexFlow;

import cn.schoolwow.quickdao.annotation.IndexType;
import cn.schoolwow.quickdao.domain.database.ddl.IndexField;
import cn.schoolwow.quickdao.domain.entity.Entity;
import cn.schoolwow.quickdao.module.database.parent.domain.ResultSetConsumer;
import cn.schoolwow.quickdao.module.database.parent.flow.executor.ExecuteQueryConnectionFlow;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;

import java.sql.ResultSet;
import java.util.Arrays;

public class GetEntityIndexByPostgresFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        Entity entity = (Entity) flowContext.checkData("entity");
        flowContext.startFlow(new ExecuteQueryConnectionFlow())
                .putTemporaryData("sql", "select tablename,indexname,indexdef from pg_indexes where tablename = ?;")
                .putTemporaryData("parameters", Arrays.asList(entity.tableName))
                .putReturnData("resultSetConsumer",new ResultSetConsumer() {
                    @Override
                    public void consumeResultSet(ResultSet resultSet) throws Exception {
                        while(resultSet.next()){
                            IndexField indexField = new IndexField();
                            indexField.tableName = resultSet.getString("tablename");
                            indexField.indexName = resultSet.getString("indexname");

                            String def = resultSet.getString("indexdef");
                            if (def.contains("UNIQUE INDEX")) {
                                indexField.indexType = IndexType.UNIQUE;
                            } else {
                                indexField.indexType = IndexType.NORMAL;
                            }
                            indexField.using = def.substring(def.indexOf("USING") + "USING".length(), def.indexOf("(")).replace("\"", "").trim();
                            String[] columns = def.substring(def.indexOf("(") + 1, def.indexOf(")")).split(",");
                            for (int i = 0; i < columns.length; i++) {
                                indexField.columns.add(columns[i].trim());
                            }
                            entity.indexFieldList.add(indexField);
                        }
                    }
                })
                .execute();
    }

    @Override
    public String name() {
        return "获取数据库索引信息-Postgres";
    }
}
